package org.tzw.template.utils;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


public class ActivityContainer {
    private Map<String, Activity> activityMap = new ConcurrentHashMap<>();
    private static ActivityContainer instance;

    //当前界面是否是主界面
    private Boolean isMainHome = false;

    private ActivityContainer() {
    }


    public boolean isMainHome() {
        return isMainHome;
    }

    public static ActivityContainer getInstance() {
        if (null == instance) {
            instance = new ActivityContainer();
        }
        return instance;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (activity.getClass().getName().contains("MainActivity")) {
            isMainHome = true;
        } else {
            isMainHome = false;
        }
        activityMap.put(activity.getClass().getName(), activity);
    }

    public Activity getActivity(String key) {
        return activityMap.get(key);
    }
    public List<Activity> getAllActivityList() {
        return new ArrayList<>(activityMap.values());
    }

    /**
     * 关闭指定的Activity
     *
     * @param activity
     */
    public void finishPage(Activity activity) {
        finishPage(activity.getClass());
    }

    /**
     * 关闭指定的Activity
     *
     * @param activity
     */
    public void finishPage(Class<?> activity) {
        Activity act = activityMap.get(activity.getName());
        if (act != null) {
            act.finish();
            activityMap.remove(activity.getName());
        }
    }

    /**
     * 关闭所有的Activity
     */
    public void finishAllPage() {
        Set<String> keySet = activityMap.keySet();
        for (String item : keySet) {
            activityMap.get(item).finish();
            activityMap.remove(item);
        }
    }

    /**
     * 返回跳转到指定的页面，其他也没按会被关闭
     */
    public void backTargetActivity(String targetName) {
        Set<String> keySet = activityMap.keySet();
        for (String item : keySet) {
            if (!item.equals(targetName)) {
                Activity act = activityMap.get(item);
                if (act != null) {
                    act.finish();
                    activityMap.remove(item);
                }
            }
        }
    }
}
